package com.zt.ztyh.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.ztyh.dto.FundsCount;
import com.zt.ztyh.dto.FundsDto;
import com.zt.ztyh.dto.FundsUserDto;
import com.zt.ztyh.entity.Funds;
import com.zt.ztyh.entity.Fundsinfo;
import com.zt.ztyh.entity.User;
import com.zt.ztyh.entity.ZtyhFundsUser;
import com.zt.ztyh.exception.ZhentaoException;
import com.zt.ztyh.mapper.FundsinfoMapper;
import com.zt.ztyh.service.FundsService;
import com.zt.ztyh.mapper.FundsMapper;
import com.zt.ztyh.service.FundsUserService;

import com.zt.ztyh.service.UnLoanUserService;
import com.zt.ztyh.utils.IdWorker;
import com.zt.ztyh.vo.UserInfoVo;
import com.zt.ztyh.vo.common.ResultCodeEnum;
import com.zt.ztyh.vo.funds.FundsUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 贾天旺
* @description 针对表【ztyh_funds】的数据库操作Service实现
* @createDate 2024-04-03 19:49:42
*/
@Service
public class FundsServiceImpl extends ServiceImpl<FundsMapper, Funds>
    implements FundsService{

    @Autowired
    private FundsMapper fundsMapper;

    @Autowired
    private FundsinfoMapper fundsinfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired(required = false)
    private FundsUserService fundsUserService;

    /**
     * 从redis中取出token来进行用户喜欢推送
     * 判断模糊查询以及月、年化率、风险等级排序
     * 没有则查询产品列表和条件查询
     * @param page
     * @param limit
     * @param fundsDto
     * @param
     * @return
     */
    @Override
    public Page<Funds> findFunds(Integer page, Integer limit, FundsDto fundsDto) {

        if(ObjectUtil.isNotEmpty(fundsDto.getFname())){
            return this.fundsMapper.selectPage(new Page<Funds>(page,limit),new QueryWrapper<Funds>().like("fname",fundsDto.getFname()).eq("status",0));
        }
        if(fundsDto.getRisk()!=null){

            return this.fundsMapper.selectPage(new Page<Funds>(page,limit),new QueryWrapper<Funds>().orderByDesc("risk").eq("status",0));
        }
        if(ObjectUtil.isNotEmpty(fundsDto.getCreateTimeBegin()) || ObjectUtil.isNotEmpty(fundsDto.getCreateTimeEnd())){

            return this.fundsMapper.selectPage(new Page<Funds>(page,limit),new QueryWrapper<Funds>().between("createTime",fundsDto.getCreateTimeBegin(),fundsDto.getCreateTimeEnd()).eq("status",0));
        }
        if(ObjectUtil.isNotEmpty(fundsDto.getMouthrate())){

            return this.fundsMapper.selectPage(new Page<Funds>(page,limit),new QueryWrapper<Funds>().orderByDesc("mouthrate").eq("status",0));
        }
        if(ObjectUtil.isNotEmpty(fundsDto.getYearrate())){

            return this.fundsMapper.selectPage(new Page<Funds>(page,limit),new QueryWrapper<Funds>().orderByDesc("yearrate").eq("status",0));
        }

        return this.fundsMapper.selectPage(new Page<Funds>(page,limit),new QueryWrapper<Funds>().eq("status",0));
    }

    @Override
    public List<Fundsinfo> findFundsInfo(Long fid) {
        return this.fundsinfoMapper.selectList(new QueryWrapper<Fundsinfo>().eq("id",fid));
    }
    @Autowired
    private UnLoanUserService unLoanUserService;

    /**
     * 购买理财产品 获取用户id ,产品id,总价
     * @param fundsDto
     */
    @Override
    public void buyFunds(String token,FundsDto fundsDto) {
        System.out.println("=======>"+fundsDto);
        Fundsinfo fundsinfo = fundsinfoMapper.selectById(fundsDto.getFid());
        //商品数量减一
        if(fundsinfo.getShare()>=1){
            //判断用户余额
            User user = this.fundsMapper.selectUserUn(fundsDto.getUid());
            fundsinfo.setShare(fundsinfo.getShare()-1);
            int i = fundsinfoMapper.updateById(fundsinfo);
            if(i>=1){
                //减去用户所剩的余额
                //this.fundsMapper.unUpdateLoan(fundsUserDto.getUid(),fundsUserDto.getAmount(),0);
                UserInfoVo userInfoVo=new UserInfoVo();
                userInfoVo.setId(fundsDto.getUid());
                userInfoVo.setAmount(fundsDto.getAmount());
                userInfoVo.setS(1);
                boolean b = this.unLoanUserService.updateUserinfo(token, userInfoVo);
                if(b){
                    //添加到用户产品表
                    IdWorker idWorker=new IdWorker();
                    long id = idWorker.nextId();
                    fundsDto.setId(id);
                    this.fundsUserService.addFunds(fundsDto);
                }
//                this.fundsMapper.addFunds(fundsDto.getUid(),fundsDto.getFid(),fundsDto.getAmount(),id);
            }
        }
        //为空
        if(fundsinfo.getShare()<=0){
            throw new ZhentaoException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public Page<FundsUserVo> findByUser(Integer page,Integer limit,FundsDto fundsDto) throws ParseException {
//        return this.fundsUserService.findByUser(userId,state);
        //理财收益
//        List<FundsUserVo> byUser = this.fundsMapper.findByUser(userId);
//        if(ObjectUtil.isNotEmpty(fundsDto.getFname())){
//
//        }
        Page<FundsUserVo> byUser =null;

//        Map<String,Object> map=new HashMap<>();
//        map.put("id",fundsDto.getId());
//        map.put("fname",fundsDto.getFname());
//        map.put("createTimeBegin",fundsDto.getCreateTimeBegin());
//        map.put("createTimeEnd",fundsDto.getCreateTimeEnd());
//        map.put("risk",fundsDto.getRisk());
        if(ObjectUtil.isNotEmpty(fundsDto)){
            fundsDto.setPage(page);
            fundsDto.setLimit(limit);
//            byUser = this.fundsMapper.findByUser(new Page<FundsUserVo>(page,limit),fundsDto);
                byUser = this.fundsUserService.findByUser(fundsDto);
        }
        List<FundsUserVo> byUser1 =new ArrayList<>();
        Page<FundsUserVo> fundsUserVoPage=new Page<>(page,limit);
        for(FundsUserVo u:byUser.getRecords()){
            if(u.getState()==0){
                //不为空取出用户购买的金额
                BigDecimal amount = u.getAmount();
                //计算所得出的钱数 //利率=本金*利率*天数
                Date createTime = u.getCreateTime();
                Date date = new Date();
                System.out.println("现在时间==>"+date);
                System.out.println("购买时间==>"+createTime);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                long between = DateUtil.between(simpleDateFormat.parse(simpleDateFormat.format(createTime)), date, DateUnit.DAY);
//                long between = DateUtil.between(createTime,date, DateUnit.DAY);
                System.out.println("之间所隔的天数="+between);
                BigDecimal rate = amount.multiply(u.getRate()).multiply(BigDecimal.valueOf(between)).divide(BigDecimal.valueOf(365),2, BigDecimal.ROUND_HALF_DOWN);
                System.out.println("========>所计算出的利率="+rate);
                u.setRedundancy1(rate);
                byUser1.add(u);
            }else{
                byUser1.add(u);
            }
        }
        byUser.setRecords(byUser1);
        BeanUtils.copyProperties(byUser,fundsUserVoPage);
        return fundsUserVoPage;
//        fundsUserVoPage.setRecords(byUser1);
//        return fundsUserVoPage;
    }

    @Override
    public List<FundsCount> findByFunds(Long fundsId) {
        return this.fundsUserService.findByFunds(fundsId);
    }

    /**
     * 购买理财产品后赎回
     * 根据fid查询出现在理财产品现在的利率，然后获取用户的购买的余额，然后计算出赎回金额,并返回前端用户id,及赎回金额
     * @param fundsUserDto
     *
     * @return
     */
    @Override
    public void  updateFunds(String token,FundsUserDto fundsUserDto) throws ParseException {
        System.out.println("====>="+fundsUserDto);
        //先查询出理财产品的现在的利率
        Fundsinfo fundsinfo = this.fundsinfoMapper.selectById(fundsUserDto.getFid());
        if(fundsinfo!=null){
            //获取用户购买的金额
            ZtyhFundsUser ztyhFundsUser = this.fundsUserService.fundsUserById(fundsUserDto.getId());
//            ZtyhFundsUser ztyhFundsUser = this.fundsMapper.fundsUserById(fundsUserDto.getId());
            System.out.println("=====>用户信息"+ztyhFundsUser);
            if(ObjectUtil.isEmpty(ztyhFundsUser)){
                throw new ZhentaoException(ResultCodeEnum.DATA_ERROR);
            }
            //不为空取出用户购买的金额
            BigDecimal amount = ztyhFundsUser.getAmount();
            //计算所得出的钱数 //利率=本金*利率*天数/365
            Date createTime = ztyhFundsUser.getCreateTime();
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            long between = DateUtil.between(simpleDateFormat.parse(simpleDateFormat.format(createTime)), date, DateUnit.DAY);
            System.out.println("之间所隔的天数="+between);
            BigDecimal rate = amount.multiply(fundsinfo.getRate()).multiply(BigDecimal.valueOf(between)).divide(BigDecimal.valueOf(365),2, BigDecimal.ROUND_HALF_UP);
            System.out.println("========>所计算出的利率="+rate);
            BigDecimal total=amount.add(rate);
            System.out.println("========>总共所得出的钱数"+total);
            //进行转换并传回
            fundsUserDto.setAmount(total);
            fundsUserDto.setRedundancy1(rate);
            fundsUserDto.setUpdateTime(new Date());
            System.out.println("==>total"+fundsUserDto.getAmount());
            //进行修改中间表
             boolean i=this.fundsUserService.updateFunds(fundsUserDto);
//            int i = this.fundsMapper.updateFunds(fundsUserDto);
            if(i){
                //进行用户转账
                UserInfoVo userInfoVo=new UserInfoVo();
                userInfoVo.setId(fundsUserDto.getUid());
                userInfoVo.setAmount(fundsUserDto.getAmount());
                userInfoVo.setS(0);
                this.unLoanUserService.updateUserinfo(token,userInfoVo);
//                this.fundsMapper.unUpdateLoan(fundsUserDto.getUid(),fundsUserDto.getAmount(),0);
//                this.fundsMapper.unUpdateLoan(fundsUserDto.getUid(),fundsUserDto.getAmount(),1);
            }
        }else{
            throw new ZhentaoException(ResultCodeEnum.DATA_ERROR);
        }
    }

}




